package com.feeyo.prophet.plugins;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.feeyo.llm.agent.engine.ResultScheme;
import com.feeyo.prophet.pojo.action.fleet.FleetAttributesEventVo;
import com.feeyo.prophet.pojo.action.fleet.FleetAttributesResp;
import com.feeyo.prophet.pojo.enums.ChartEnum;
import com.feeyo.prophet.pojo.vo.chart.BarChart;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 民航看板辅助
 */
@Slf4j
public class FlightScheduleActionUtils {
    /**
     * 获取 FcateType
     */
    public static String categoriesStr(JSONArray jsonArray) {
        List<String> list = jsonArray.toJavaList(String.class);
        return String.join(",", list);
    }

    /**
     * 数据替换
     */
    public static String dateMatcher(String input) {
        // 编译正则表达式，匹配只包含 '0' 的字符串
        Pattern zeroOnlyPattern = Pattern.compile("(?i)^(0+)$");
        // 替换第一个匹配的字符串为 "暂无统计"
        String replaced = input;
        // 逐个检查字符串中的每个子字符串
        for (Matcher matcher = zeroOnlyPattern.matcher(input); matcher.find(); ) {
            // 如果匹配的字符串只包含 '0'，则替换为 "暂无统计"
            if (matcher.group().matches("^0+$")) {
                replaced = replaced.replaceFirst(matcher.group(), "暂无统计");
                break;
            }
        }
        return replaced;
    }


    /**
     * 数据转明细
     */
    public static List<FleetAttributesResp> getFleetAttributesDetail(JSONArray fleetDetailArray, List<String> aircraftList, List<String> aircraftTypeList) {
        List<FleetAttributesResp> airportStatisticList = Lists.newArrayList();
        for (int i = 0; i < fleetDetailArray.size(); i++) {
            JSONObject resultSet = fleetDetailArray.getJSONObject(i);
            FleetAttributesResp fleet = new FleetAttributesResp();
            fleet.setAircraftId(resultSet.getInteger("aircraftId"));
            fleet.setSerialNumber(resultSet.getString("serialNumber"));
            fleet.setHexcode(resultSet.getString("hexcode"));
            fleet.setAircraftMasterSeries(resultSet.getString("aircraftMasterSeries"));
            String aircraftStatus = resultSet.getString("aircraftStatus");
            if (!CollectionUtils.isEmpty(aircraftList) && !aircraftList.contains(aircraftStatus)) {
                continue;
            }
            String aircraftType = resultSet.getString("aircraftType");
            if (!CollectionUtils.isEmpty(aircraftTypeList) && !aircraftTypeList.contains(aircraftType)) {
                continue;
            }
            fleet.setAircraftStatus(resultSet.getString("aircraftStatus"));
            fleet.setManager(resultSet.getString("manager"));
            fleet.setOperator(resultSet.getString("operator"));
            fleet.setBuildYear(resultSet.getInteger("buildYear"));
            airportStatisticList.add(fleet);
        }
        return airportStatisticList;
    }

    /**
     * 数据赋值
     */
    public static void getCategoryChart(List<Double> cargoVolumeList, List<BarChart.Axis> yAxisList, List<BarChart.Data> dataList, String name, String formatter, ChartEnum dataType) {
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(cargoVolumeList)) {
            BarChart.Axis yAxis = new BarChart.Axis();
            yAxis.setName(name);
            yAxis.setFormatter(formatter);
            yAxisList.add(yAxis);
            BarChart.Data data = new BarChart.Data();
            data.setName(name);
            data.setType(dataType.getCode());
            data.setValue(cargoVolumeList);
            data.setYAxisIndex(yAxisList.size());
            dataList.add(data);
        }
    }


    public static List<FleetAttributesEventVo> getFleetAttributesEventDetail(JSONArray fleetDetailArray) {
        List<FleetAttributesEventVo> airportStatisticList = Lists.newArrayList();
        for (int i = 0; i < fleetDetailArray.size(); i++) {
            JSONObject resultSet = fleetDetailArray.getJSONObject(i);
            FleetAttributesEventVo fleet = new FleetAttributesEventVo();
            fleet.setEventStartDate(timeChangeToShanghai(resultSet.getString("eventStartDate")));
            fleet.setStartEvent(resultSet.getString("startEvent"));
            fleet.setManager(resultSet.getString("manager"));
            fleet.setOperator(resultSet.getString("operator"));
            airportStatisticList.add(fleet);
        }
        return airportStatisticList;
    }

    /**
     * 数据时间转换
     *
     * @param eventDate 事件时间
     */
    public static String timeChangeToShanghai(String eventDate) {
        // 解析输入字符串为 ZonedDateTime 对象
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(eventDate);
        // 将时区调整为 +8
        ZonedDateTime adjustedDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
        // 将日期转换为指定的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return adjustedDateTime.format(formatter);
    }

    /**
     * 时间戳转上海时间
     */
    public static String timeStampToShanghai(Long timeStamp) {
        // 解析输入字符串为 ZonedDateTime 对象
        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.ofEpochSecond(timeStamp), ZoneId.of("Asia/Shanghai"));
        // 将日期转换为指定的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return zonedDateTime.format(formatter);
    }

    /**
     * 将指定字段从对象列表中提取出来，并放入 JSON 对象列表中
     *
     * @param fields           需要提取的字段名列表
     * @param dynamicRespList  包含数据的对象列表
     * @param <T>              对象类型
     * @return 包含提取字段的 JSON 对象列表
     */
    public static <T> List<JSONObject> getNeedDataList(List<String> fields, List<T> dynamicRespList) {
        List<JSONObject> resultList = Lists.newArrayList();
        for (T dynamicResp : dynamicRespList) {
            JSONObject jsonObject = new JSONObject();
            for (String fieldName : fields) {
                try {
                    Field field;
                    try {
                        field = dynamicResp.getClass().getDeclaredField(fieldName);
                    } catch (NoSuchFieldException e) {
                        field = dynamicResp.getClass().getField(fieldName);
                    }
                    // 设置为可访问
                    field.setAccessible(true);
                    Object value = field.get(dynamicResp);
                    if (value != null) {
                        jsonObject.put(fieldName, value);
                    }
                } catch (NoSuchFieldException | IllegalAccessException ignored) {
                    log.debug("字段{}不存在", fieldName);
                }
            }
            resultList.add(jsonObject);
        }
        return resultList;
    }

    /**
     * 字段筛选。从全量字段中筛选出需要的字段
     * @param fields            字段列表
     * @param allResultScheme   全量字段
     */
    public static ResultScheme resultScheme(List<String> fields, ResultScheme allResultScheme){
        ResultScheme resultScheme = new ResultScheme();
        List<ResultScheme.ResultAttach> resultAttachList = Lists.newArrayList();
        List<ResultScheme.ResultAttach> allResultList = allResultScheme.getResultAttachList();
        for (ResultScheme.ResultAttach resultAttach : allResultList) {
            if(fields.contains(resultAttach.getName())){
                resultAttachList.add(resultAttach);
            }
        }
        resultScheme.setResultAttachList(resultAttachList);
        return resultScheme;
    }
}
